package cn.ylz.ylmall.common.qiniuyun;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Slf4j
public class Qiniuyun {
    private static String QINIU_DOMAIN = "http://yunlan.shop/";
    public String upFile(InputStream inputStream, String fileName, String projectName) {
        String url = null;
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
        String accessKey = "pJeaMubFmJIwxY9-HdRl_4ZkugJX9R4aOkKAwFP3";
        String secretKey = "aOLxcbkEOFU5SubY5yNcqh5e6vV59iDmBfJWJol5";
        String bucket = "yunlan";
//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = projectName + "/" + fileName;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        log.debug("上传文件至云存储...");
        try {
            Response response = uploadManager.put(inputStream, key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            if (response.isOK() && response.isJson()) {
                log.debug("上传文件成功...");
                // 返回地址
                return QINIU_DOMAIN + URLEncoder.encode((String) JSONObject.parseObject(response.bodyString()).get("key"), "UTF-8");
            } else {
                log.warn("文件上传失败...");
                System.err.println(response.toString());
                return null;
            }


        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
            //ignore
        }
        return null;
    }

}
